package com.ruoyi.consumer.utils.pay;

import com.alibaba.fastjson2.JSONObject;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.model.OrderQueryModel;
import com.ijpay.wxpay.model.RefundModel;
import com.ruoyi.consumer.domain.pay.JsApiOrderModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.security.SecureRandom;
import java.util.Map;
import java.util.Random;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

@Component
public class Payment {

    private static String appid;

    private static String mchid;

    private static String notifyUrl;

    private static String mchKey;

    @Value("${wx.appid}")
    public void setAppid(String appid) {
        Payment.appid = appid;
    }

    @Value("${wx.notifyUrl}")
    public void setNotifyUrl(String notifyUrl) {
        Payment.notifyUrl = notifyUrl;
    }

    @Value("${wx.mchKey}")
    public void setMchKey(String mchKey) {
        Payment.mchKey = mchKey;
    }

    @Value("${wx.mchid}")
    public void setMchid(String mchid) {
        Payment.mchid = mchid;
    }


    public JSONObject paymentPay(JsApiOrderModel order) {
        String ip = "124.70.218.167";
        Map<String, String> params = JsApiOrderModel.builder()
                .appid(appid)
                .mch_id(mchid)
                // 随机字符串
                .nonce_str(order.getNonce_str())
                // 商品描述
                .body(order.getBody())
                //额外参数
                .attach(order.getAttach())
                // 商户订单号
                .out_trade_no(order.getOut_trade_no())
                // 标价金额
                .total_fee(order.getTotal_fee())
                // 终端IP
                .spbill_create_ip(ip)
                // 通知地址
                .notify_url(order.getNotify_url())
                // 交易类型
                .trade_type(TradeType.JSAPI.getTradeType())
                .openid(order.getOpenid())
                .build()
                .createSign(mchKey, SignType.MD5);
        //进行数据加密封装
        String xmlResult = WxPayApi.pushOrder(false, params);
        Map<String, String> resultMap = WxPayKit.xmlToMap(xmlResult);
        if (StringUtils.equals(resultMap.get("return_code"), "SUCCESS")) {
            String prepayId = resultMap.get("prepay_id");
            Map<String, String> packageParams = WxPayKit.prepayIdCreateSign(prepayId, appid,
                    mchKey, SignType.MD5);
            return new JSONObject(packageParams);
        }
        return null;
    }


    public String queryOrder(String outTradeNo) {
        try {

            Map<String, String> params = OrderQueryModel.builder()
                    .appid(appid)
                    .mch_id(mchid)
                    .out_trade_no(outTradeNo)
                    .nonce_str(WxPayKit.generateStr())
                    .build()
                    .createSign(mchKey, SignType.MD5);
            String query = WxPayApi.orderQuery(params);
            return query;
        } catch (Exception e) {
            e.printStackTrace();
            return "系统错误";
        }
    }


    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    // 生成指定长度的随机字符串
    public static String generateRandomString(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("Length must be greater than 0");
        }

        StringBuilder randomString = new StringBuilder(length);
        Random random = new SecureRandom();

        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(CHARACTERS.length());
            randomString.append(CHARACTERS.charAt(randomIndex));
        }

        return randomString.toString();
    }

}
